package com.ruoyi.fun.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.access.prepost.PreAuthorize;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.fun.domain.EcProduct;
import com.ruoyi.fun.domain.EcCategory;
import com.ruoyi.fun.domain.EcProductSku;
import com.ruoyi.fun.domain.EcProductComment;
import com.ruoyi.fun.service.IEcProductService;
import com.ruoyi.fun.service.IEcCategoryService;
import com.ruoyi.fun.service.IEcProductSkuService;
import com.ruoyi.fun.service.IEcProductCommentService;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;

/**
 * 移动端商品Controller（无需权限验证）
 * 
 * @author ruoyi
 * @date 2025-08-10
 */
@Anonymous
@RestController
@RequestMapping("/mobile/product")
public class EcMobileProductController extends BaseController
{
    @Autowired
    private IEcProductService ecProductService;
    
    @Autowired
    private IEcCategoryService ecCategoryService;
    
    @Autowired
    private IEcProductSkuService ecProductSkuService;
    
    @Autowired
    private IEcProductCommentService ecProductCommentService;
    
    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private com.ruoyi.fun.service.IEcBrandService ecBrandService;
    
    // 缓存键前缀
    private static final String CACHE_PREFIX = "mobile:product:";
    // 缓存过期时间（10分钟）
    private static final int CACHE_EXPIRE_TIME = 10;

    /**
     * 获取当前页码
     */
    private Integer getPageNum() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        return pageDomain.getPageNum() != null ? pageDomain.getPageNum() : 1;
    }

    /**
     * 获取每页大小
     */
    private Integer getPageSize() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        return pageDomain.getPageSize() != null ? pageDomain.getPageSize() : 10;
    }

    /**
     * 清空指定租户的商品缓存
     */
    public void clearProductCache(Long orgId) {
        try {
            // 清空热销商品缓存
            Collection<String> hotKeys = redisCache.keys(CACHE_PREFIX + "hot:" + orgId + ":*");
            if (hotKeys != null && !hotKeys.isEmpty()) {
                redisCache.deleteObject(hotKeys);
            }
            
            // 清空推荐商品缓存
            Collection<String> recommendKeys = redisCache.keys(CACHE_PREFIX + "recommend:" + orgId + ":*");
            if (recommendKeys != null && !recommendKeys.isEmpty()) {
                redisCache.deleteObject(recommendKeys);
            }
            
            // 清空新品商品缓存
            Collection<String> newKeys = redisCache.keys(CACHE_PREFIX + "new:" + orgId + ":*");
            if (newKeys != null && !newKeys.isEmpty()) {
                redisCache.deleteObject(newKeys);
            }
            
            // 清空商品列表缓存
            Collection<String> listKeys = redisCache.keys(CACHE_PREFIX + "list:" + orgId + ":*");
            if (listKeys != null && !listKeys.isEmpty()) {
                redisCache.deleteObject(listKeys);
            }
        } catch (Exception e) {
            // 缓存清除失败不影响业务逻辑，记录日志即可
            System.err.println("清除商品缓存失败: " + e.getMessage());
        }
    }
    
    /**
     * 清空所有商品缓存
     */
    public void clearAllProductCache() {
        try {
            Collection<String> keys = redisCache.keys(CACHE_PREFIX + "*");
            if (keys != null && !keys.isEmpty()) {
                redisCache.deleteObject(keys);
            }
        } catch (Exception e) {
            // 缓存清除失败不影响业务逻辑，记录日志即可
            System.err.println("清除所有商品缓存失败: " + e.getMessage());
        }
    }

    /**
     * 清空所有商品缓存的API接口
     */
    @GetMapping("/clearAllCache")
    public AjaxResult clearAllCache() {
        try {
            clearAllProductCache();
            return AjaxResult.success("缓存清空成功");
        } catch (Exception e) {
            return AjaxResult.error("缓存清空失败: " + e.getMessage());
        }
    }

    /**
     * 清空指定租户商品缓存的API接口
     */
    @GetMapping("/clearCache")
    public AjaxResult clearCache() {
        try {
            Long orgId = getOrgId();
            clearProductCache(orgId);
            return AjaxResult.success("租户缓存清空成功");
        } catch (Exception e) {
            return AjaxResult.error("租户缓存清空失败: " + e.getMessage());
        }
    }

    /**
     * 查询热销商品列表
     * @param orgId 组织ID，如果不传则默认使用103
     */
    @GetMapping("/hot")
    public TableDataInfo getHotProducts(EcProduct ecProduct, Long orgId)
    {
        // 如果前端没有传递orgId，则使用默认值
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        System.out.println("[移动端热销商品] 使用组织ID: " + orgId);
        
        String cacheKey = CACHE_PREFIX + "hot:" + orgId + ":" + getPageNum() + ":" + getPageSize();
        
        // 尝试从缓存获取数据
        TableDataInfo cachedData = redisCache.getCacheObject(cacheKey);
        if (cachedData != null) {
            System.out.println("[移动端热销商品] 从缓存获取数据");
            return cachedData;
        }
        
        // 设置热销商品查询条件
        ecProduct.setIsHot("1");
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        ecProduct.setOrgId(orgId);
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        
        // 确保list不为null
        if (list == null) {
            list = new ArrayList<>();
        }
        
        System.out.println("[移动端热销商品] 查询到商品数量: " + list.size());
        
        TableDataInfo result = getDataTable(list);
        
        // 将结果存入缓存
        redisCache.setCacheObject(cacheKey, result, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        
        return result;
    }

    /**
     * 查询推荐商品列表
     * @param orgId 组织ID，如果不传则默认使用103
     */
    @GetMapping("/recommend")
    public TableDataInfo getRecommendProducts(EcProduct ecProduct, Long orgId)
    {
        // 如果前端没有传递orgId，则使用默认值
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        System.out.println("[移动端推荐商品] 使用组织ID: " + orgId);
        
        String cacheKey = CACHE_PREFIX + "recommend:" + orgId + ":" + getPageNum() + ":" + getPageSize();
        
        // 尝试从缓存获取数据
        TableDataInfo cachedData = redisCache.getCacheObject(cacheKey);
        if (cachedData != null) {
            System.out.println("[移动端推荐商品] 从缓存获取数据");
            return cachedData;
        }
        
        // 设置推荐商品查询条件
        ecProduct.setIsRecommend("1");
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        ecProduct.setOrgId(orgId);
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        
        // 确保list不为null
        if (list == null) {
            list = new ArrayList<>();
        }
        
        System.out.println("[移动端推荐商品] 查询到商品数量: " + list.size());
        
        TableDataInfo result = getDataTable(list);
        
        // 将结果存入缓存
        redisCache.setCacheObject(cacheKey, result, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        
        return result;
    }

    /**
     * 查询新品商品列表
     */
    @GetMapping("/new")
    public TableDataInfo getNewProducts(EcProduct ecProduct)
    {
        Long orgId = getOrgId();
        String cacheKey = CACHE_PREFIX + "new:" + orgId + ":" + getPageNum() + ":" + getPageSize();
        
        // 尝试从缓存获取数据
        TableDataInfo cachedData = redisCache.getCacheObject(cacheKey);
        if (cachedData != null) {
            return cachedData;
        }
        
        // 设置新品商品查询条件
        ecProduct.setIsNew("1");
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        ecProduct.setOrgId(orgId);
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        TableDataInfo result = getDataTable(list);
        
        // 将结果存入缓存
        redisCache.setCacheObject(cacheKey, result, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        
        return result;
    }

    /**
     * 查询商品列表
     * @param orgId 组织ID，如果不传则默认使用103
     */
    @GetMapping("/list")
    public TableDataInfo list(EcProduct ecProduct, Long orgId)
    {
        // 如果前端没有传递orgId，则使用默认值
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        System.out.println("[移动端商品列表] 使用组织ID: " + orgId);
        
        // 构建缓存键，包含查询条件的哈希值
        String queryHash = String.valueOf((ecProduct.getProductName() + ecProduct.getCategoryId() + ecProduct.getBrandId()).hashCode());
        String cacheKey = CACHE_PREFIX + "list:" + orgId + ":" + getPageNum() + ":" + getPageSize() + ":" + queryHash;
        
        // 尝试从缓存获取数据
        TableDataInfo cachedData = redisCache.getCacheObject(cacheKey);
        if (cachedData != null) {
            System.out.println("[移动端商品列表] 从缓存获取数据");
            return cachedData;
        }
        
        // 只返回已发布且正常状态的商品
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        ecProduct.setOrgId(orgId);
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        
        // 确保list不为null
        if (list == null) {
            list = new ArrayList<>();
        }
        
        System.out.println("[移动端商品列表] 查询到商品数量: " + list.size());
        
        TableDataInfo result = getDataTable(list);
        
        // 将结果存入缓存
        redisCache.setCacheObject(cacheKey, result, CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        
        return result;
    }
    
    /**
     * 根据分类查询商品列表
     */
    @GetMapping("/category/{categoryId}")
    public TableDataInfo getProductsByCategory(@PathVariable Long categoryId, EcProduct ecProduct)
    {
        // 设置分类查询条件
        ecProduct.setCategoryId(categoryId);
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        ecProduct.setOrgId(getOrgId());
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        return getDataTable(list);
    }
    
    /**
     * 根据分类查询商品列表（通过参数传递分类ID）
     * @param categoryId 分类ID
     * @param orgId 组织ID，如果不传则默认使用103
     */
    @GetMapping("/category")
    public TableDataInfo getProductsByCategoryParam(@RequestParam("categoryId") Long categoryId, Long orgId, EcProduct ecProduct)
    {
        // 如果前端没有传递orgId，则使用默认值103
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        System.out.println("[移动端按分类查询商品] 分类ID: " + categoryId + ", 组织ID: " + orgId);
        
        // 设置分类查询条件
        ecProduct.setCategoryId(categoryId);
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        ecProduct.setOrgId(orgId);
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductList(ecProduct);
        
        // 确保list不为null
        if (list == null) {
            list = new ArrayList<>();
        }
        
        System.out.println("[移动端按分类查询商品] 查询到商品数量: " + list.size());
        
        return getDataTable(list);
    }
    
    /**
     * 按分类查询商品列表（包括子分类）
     */
    @GetMapping("/listByCategory")
    public TableDataInfo listByCategory(@RequestParam("categoryId") Long categoryId, EcProduct ecProduct)
    {
        // 只返回已发布且正常状态的商品
        ecProduct.setPublishStatus("1");
        ecProduct.setStatus("0");
        
        // 获取当前分类及其所有子分类的ID列表
        List<Long> categoryIds = getAllCategoryIds(categoryId);
        
        startPage();
        List<EcProduct> list = ecProductService.selectEcProductListByCategoryIds(categoryIds);
        return getDataTable(list);
    }
    
    /**
     * 获取指定分类及其所有子分类的ID列表
     */
    private List<Long> getAllCategoryIds(Long categoryId) {
        List<Long> categoryIds = new ArrayList<>();
        categoryIds.add(categoryId);
        
        // 查询所有分类
        EcCategory queryCategory = new EcCategory();
        queryCategory.setStatus("0");
        List<EcCategory> allCategories = ecCategoryService.selectEcCategoryList(queryCategory);
        
        // 递归查找所有子分类
        findAllChildCategoryIds(categoryId, allCategories, categoryIds);
        
        return categoryIds;
    }
    
    /**
     * 获取商品详细信息
     */
    @GetMapping(value = "/info/{productId}")
    public AjaxResult getProductInfo(@PathVariable("productId") Long productId)
    {
        EcProduct product = ecProductService.selectEcProductByProductIdAndOrgId(productId, getOrgId());
        if (product == null || !"1".equals(product.getPublishStatus()) || !"0".equals(product.getStatus())) {
            return error("商品不存在或已下架");
        }
        
        // 更新商品浏览量+1
        try {
            ecProductService.updateProductViewCount(productId, 1);
        } catch (Exception e) {
            System.out.println("更新商品浏览量失败: " + e.getMessage());
        }
        
        return success(product);
    }
    
    /**
     * 获取商品详情（前端兼容接口）
     */
    @GetMapping("/{productId}")
    public AjaxResult getMobileProductDetail(@PathVariable("productId") Long productId, @RequestParam(value = "orgId", required = false) Long orgId)
    {
        System.out.println("=== 移动端商品详情API调用 ===");
        System.out.println("商品ID: " + productId);
        
        // 使用传入的orgId参数，如果为空则使用默认值103
        Long targetOrgId = (orgId != null) ? orgId : getOrgId();
        System.out.println("目标组织ID: " + targetOrgId);
        
        // 获取商品详情（支持org_id隔离）
        EcProduct product = ecProductService.selectEcProductByProductIdAndOrgId(productId, targetOrgId);
        if (product == null) {
            System.out.println("商品不存在或不属于当前组织: " + productId);
            return AjaxResult.error("商品不存在");
        }
        
        System.out.println("商品信息: " + product.getProductName());
        System.out.println("发布状态: " + product.getPublishStatus());
        System.out.println("商品状态: " + product.getStatus());
        
        // 检查商品状态
        if (!"1".equals(product.getPublishStatus()) || !"0".equals(product.getStatus())) {
            System.out.println("商品状态不可用");
            return AjaxResult.error("商品已下架或不可用");
        }
        
        // 获取商品SKU列表（支持org_id隔离）
        EcProductSku skuQuery = new EcProductSku();
        skuQuery.setProductId(productId);
        skuQuery.setOrgId(targetOrgId);
        skuQuery.setStatus("0"); // 只获取正常状态的SKU
        List<EcProductSku> skuList = ecProductSkuService.selectEcProductSkuListByOrgId(skuQuery, targetOrgId);
        
        System.out.println("=== SKU查询结果 ===");
        System.out.println("SKU数量: " + (skuList != null ? skuList.size() : 0));
        
        // 打印每个SKU的详细信息，特别是权限相关字段
        if (skuList != null && !skuList.isEmpty()) {
            for (int i = 0; i < skuList.size(); i++) {
                EcProductSku sku = skuList.get(i);
                System.out.println("=== SKU[" + i + "] 详细信息 ===");
                System.out.println("SKU ID: " + sku.getSkuId());
                System.out.println("SKU名称: " + sku.getSkuName());
                System.out.println("is_vip_buy值: " + sku.getIsVipBuy() + " (类型: " + (sku.getIsVipBuy() != null ? sku.getIsVipBuy().getClass().getSimpleName() : "null") + ")");
                System.out.println("buy_white_list值: " + sku.getBuyWhiteList() + " (类型: " + (sku.getBuyWhiteList() != null ? sku.getBuyWhiteList().getClass().getSimpleName() : "null") + ")");
                System.out.println("组织ID: " + sku.getOrgId());
                System.out.println("状态: " + sku.getStatus());
            }
        }
        
        // 允许匿名用户查看基础信息（含价格与库存）；仍建议隐藏内部字段（如成本价、库存预警值）
        try {
            com.ruoyi.common.core.domain.model.LoginUser lu = getLoginUser();
            boolean authenticated = (lu != null);
            if (!authenticated) {
                // 匿名访问时隐藏内部字段
                try {
                    product.setCostPrice(null);
                    product.setLowStock(null);
                    if (skuList != null) {
                        for (EcProductSku sku : skuList) {
                            sku.setCostPrice(null);
                            sku.setLowStock(null);
                        }
                    }
                } catch (Exception e) {
                    System.out.println("匿名用户内部字段隐藏失败: " + e.getMessage());
                }
            }
        } catch (Exception e) {
            // 获取登录态失败时按匿名处理，不影响业务
        }

        // 更新商品浏览量+1
        try {
            ecProductService.updateProductViewCount(productId, 1);
        } catch (Exception e) {
            System.out.println("更新商品浏览量失败: " + e.getMessage());
        }
        
        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("product", product);
        result.put("skuList", skuList);
        
        System.out.println("=== 返回数据 ===");
        System.out.println("返回结果构建完成");
        
        return AjaxResult.success(result);
    }
    
    /**
     * 获取商品详情（包含SKU信息）
     */
    @GetMapping("/detail/{productId}")
    public AjaxResult getProductDetail(@PathVariable("productId") Long productId)
    {
        System.out.println("=== 商品详情API调用 ===");
        System.out.println("商品ID: " + productId);
        System.out.println("组织ID: " + getOrgId());
        
        // 获取商品详情（支持org_id隔离）
        EcProduct product = ecProductService.selectEcProductByProductIdAndOrgId(productId, getOrgId());
        if (product == null) {
            System.out.println("商品不存在或不属于当前组织: " + productId);
            return AjaxResult.error("商品不存在");
        }
        
        System.out.println("商品信息: " + product.getProductName());
        System.out.println("发布状态: " + product.getPublishStatus());
        System.out.println("商品状态: " + product.getStatus());
        
        // 检查商品状态
        if (!"1".equals(product.getPublishStatus()) || !"0".equals(product.getStatus())) {
            System.out.println("商品状态不可用");
            return AjaxResult.error("商品已下架或不可用");
        }
        
        // 获取商品SKU列表（支持org_id隔离）
        EcProductSku skuQuery = new EcProductSku();
        skuQuery.setProductId(productId);
        skuQuery.setOrgId(getOrgId());
        skuQuery.setStatus("0"); // 只获取正常状态的SKU
        List<EcProductSku> skuList = ecProductSkuService.selectEcProductSkuListByOrgId(skuQuery, getOrgId());
        
        // 确保skuList不为null
        if (skuList == null) {
            skuList = new ArrayList<>();
        }
        
        System.out.println("=== SKU查询结果 ===");
        System.out.println("SKU数量: " + skuList.size());
        if (!skuList.isEmpty()) {
            for (EcProductSku sku : skuList) {
                System.out.println("SKU ID: " + sku.getSkuId() + ", 名称: " + sku.getSkuName() + ", 价格: " + sku.getPrice() + ", 库存: " + sku.getStock());
            }
        } else {
            System.out.println("未找到SKU数据");
        }
        
        // 获取商品评论列表（只显示前5条，支持org_id隔离）
        EcProductComment commentQuery = new EcProductComment();
        commentQuery.setProductId(productId);
        commentQuery.setOrgId(getOrgId());
        commentQuery.setShowStatus("1"); // 只获取显示状态的评论
        List<EcProductComment> commentList = ecProductCommentService.selectEcProductCommentListByOrgId(commentQuery, getOrgId());
        
        // 限制评论数量为前5条
        if (commentList != null && commentList.size() > 5) {
            commentList = commentList.subList(0, 5);
        }
        
        // 确保commentList不为null
        if (commentList == null) {
            commentList = new ArrayList<>();
        }
        
        System.out.println("=== 评论查询结果 ===");
        System.out.println("评论数量: " + commentList.size());
        if (!commentList.isEmpty()) {
            for (EcProductComment comment : commentList) {
                System.out.println("评论ID: " + comment.getCommentId() + ", 用户: " + comment.getUserName() + ", 评分: " + comment.getStar());
            }
        } else {
            System.out.println("未找到评论数据");
        }
        
        // 更新商品浏览量+1
        try {
            ecProductService.updateProductViewCount(productId, 1);
        } catch (Exception e) {
            System.out.println("更新商品浏览量失败: " + e.getMessage());
        }
        
        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("product", product);
        result.put("skuList", skuList);
        result.put("commentList", commentList);
        
        System.out.println("=== 返回数据 ===");
        System.out.println("返回结果: " + result);
        
        return AjaxResult.success(result);
    }
    
    /**
     * 递归查找所有子分类ID
     */
    private void findAllChildCategoryIds(Long parentId, List<EcCategory> allCategories, List<Long> categoryIds) {
        for (EcCategory category : allCategories) {
            if (category.getParentId() != null && category.getParentId().equals(parentId)) {
                categoryIds.add(category.getCategoryId());
                // 递归查找子分类的子分类
                findAllChildCategoryIds(category.getCategoryId(), allCategories, categoryIds);
            }
        }
    }
    
    /**
     * 获取移动端品牌详情（匿名访问）
     */
    @GetMapping("/brand/{brandId}")
    public AjaxResult getMobileBrandDetail(@PathVariable Long brandId, @RequestParam(required = false) Long orgId) {
        // 如果没有传递orgId，使用默认值103
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        System.out.println("获取移动端品牌详情，品牌ID: " + brandId + ", 组织ID: " + orgId);
        
        try {
            com.ruoyi.fun.domain.EcBrand brand = ecBrandService.selectEcBrandByBrandIdAndOrgId(brandId, orgId);
            if (brand == null) {
                System.out.println("品牌不存在，品牌ID: " + brandId + ", 组织ID: " + orgId);
                // 品牌不存在时返回成功响应但数据为null，让前端处理默认值
                return AjaxResult.success(null);
            }
            
            System.out.println("成功获取品牌详情，品牌ID: " + brandId + ", 品牌名称: " + brand.getBrandName());
            return AjaxResult.success(brand);
        } catch (Exception e) {
            System.out.println("获取品牌详情异常: " + e.getMessage());
            return AjaxResult.error("获取品牌详情失败");
        }
    }
    
    /**
     * 获取移动端分类详情（匿名访问）
     */
    @GetMapping("/categoryDetail/{categoryId}")
    public AjaxResult getMobileCategoryDetail(@PathVariable Long categoryId, @RequestParam(required = false) Long orgId) {
        // 如果没有传递orgId，使用默认值103
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        System.out.println("获取移动端分类详情，分类ID: " + categoryId + ", 组织ID: " + orgId);
        
        try {
            EcCategory category = ecCategoryService.selectEcCategoryByCategoryIdAndOrgId(categoryId, orgId);
            if (category == null) {
                System.out.println("分类不存在，分类ID: " + categoryId + ", 组织ID: " + orgId);
                return AjaxResult.error("分类不存在");
            }
            
            System.out.println("成功获取分类详情，分类ID: " + categoryId + ", 分类名称: " + category.getCategoryName());
            return AjaxResult.success(category);
        } catch (Exception e) {
            System.out.println("获取分类详情异常: " + e.getMessage());
            return AjaxResult.error("获取分类详情失败");
        }
    }

    /**
     * 获取移动端商品评价列表（匿名访问）
     */
    @GetMapping("/comment/list")
    public AjaxResult getMobileCommentList(@RequestParam("productId") Long productId, @RequestParam(value = "orgId", required = false) Long orgId,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        // 如果没有传递orgId，使用默认值103
        if (orgId == null) {
            orgId = getOrgId(); // 从BaseController获取默认组织ID
        }
        
        System.out.println("获取移动端商品评价列表，商品ID: " + productId + ", 组织ID: " + orgId + ", 页码: " + pageNum + ", 页大小: " + pageSize);
        
        try {
            // 设置分页参数
            startPage();
            
            EcProductComment commentQuery = new EcProductComment();
            commentQuery.setProductId(productId);
            commentQuery.setOrgId(orgId);
            commentQuery.setShowStatus("1"); // 只获取显示状态的评论
            
            List<EcProductComment> commentList = ecProductCommentService.selectEcProductCommentListByOrgId(commentQuery, orgId);
            
            System.out.println("评价查询结果数量: " + (commentList != null ? commentList.size() : 0));
            
            // 构建分页结果
            TableDataInfo rspData = getDataTable(commentList);
            
            return AjaxResult.success(rspData);
        } catch (Exception e) {
            System.out.println("获取商品评价列表异常: " + e.getMessage());
            return AjaxResult.error("获取商品评价列表失败");
        }
    }

    /**
     * 根据id和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:ecmobileproduct:query')")
    @GetMapping(value = "/{id}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("id") Long id, @PathVariable("orgId") Long orgId)
    {
        return success(ecProductService.selectEcProductByProductIdAndOrgId(id, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('system:ecmobileproduct:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcProduct ecProduct = new EcProduct();
        List<EcProduct> list = ecProductService.selectEcProductListByOrgId(ecProduct, orgId);
        return getDataTable(list);
    }


}
